//
//  NetworkTools.m
//  one
//
//  Created by admin on 2023/10/12.
//

#import "NetworkTools.h"

////网络工具协议
//@protocol NetworkToolsProxy <NSObject>
//
////此方法 AFNetworking 以提供 (供参考)
//@optional
//- (nullable NSURLSessionDataTask *)dataTaskWithHTTPMethod:(NSString *)method
//                                                URLString:(NSString *)URLString
//                                               parameters:(nullable id)parameters
//                                                  headers:(nullable NSDictionary <NSString *, NSString *> *)headers
//                                           uploadProgress:(nullable void (^)(NSProgress *uploadProgress))uploadProgress
//                                         downloadProgress:(nullable void (^)(NSProgress *downloadProgress))downloadProgress
//                                                  success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success
//                                                  failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure;
//@end
//
////遵守网络协议，意味着有提示
//@interface NetworkTools() <NetworkToolsProxy>
//@end
 
@implementation NetworkTools
 
+(instancetype) sharedTools{
 
    static NetworkTools *tools;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //注意：末尾需要包含 '/'
        NSURL *baseUrl = [NSURL URLWithString:@"https://mobile.zhp.geg.com.cn:7082/"];
        tools = [[self alloc]initWithBaseURL:baseUrl];
        //设置反序列化格式
        tools.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", nil];
    });
    return tools;
}
 
-(void) request:(RequestMethod)method URLString:(NSString *)URLString parameters:(nullable id)parameters finished:(void (^)(id result, NSError *error))finished{
 
    NSString *methodName = (method == GET) ? @"GET": @"POST";
    // dataTaskWithHTTPMethod 本类没有实现方法，但父类实现了
    // 在调用方法的时候，如果本类没有提供，就直接调用父类的方法，AFN 内部已经实现
//    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:methodName URLString:URLString parameters:parameters headers:nil uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        finished(responseObject,nil);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        finished(nil,error);
//        NSLog(@"%@",error);
//    }];
//    [dataTask resume];
    
    NSLog(@"%@",self.baseURL);
    
    NSString *urlString = [self.baseURL.absoluteString stringByAppendingString:URLString];
    NSLog(@"%@",urlString);
    NSURL *url = [NSURL URLWithString:urlString];
    
    
    NSData* dataParam = [parameters dataUsingEncoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url
                                                               cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                           timeoutInterval:1000];
    [request setHTTPMethod:methodName];
    [request setHTTPBody:dataParam];
    
    NSURLSession *requestSessions = [NSURLSession sharedSession];
    NSURLSessionDataTask *requestTasks = [requestSessions dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //NSLog(@"data ======= %@, response ======= %@, error ======= %@",data ,response, error);
        
        if(error==NULL){
            NSString *resultStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"响应数据正常");
            NSLog(@"-------------data start---------------");
            NSLog(@"%@",resultStr);
            NSLog(@"-------------data end-----------------");
            finished(data,nil);
        }else{
            NSLog(@"响应数据出错了");
            NSLog(@"%@",error);
            finished(nil,error);
        }
    }];
    [requestTasks resume];
}

-(void) request:(RequestMethod)method URLString:(NSString *)URLString parameters:(nullable id)parameters token:(NSString *)token finished:(void (^)(id result, NSError *error))finished{
 
    NSString *methodName = (method == GET) ? @"GET": @"POST";
    // dataTaskWithHTTPMethod 本类没有实现方法，但父类实现了
    // 在调用方法的时候，如果本类没有提供，就直接调用父类的方法，AFN 内部已经实现
//    NSURLSessionDataTask *dataTask = [self dataTaskWithHTTPMethod:methodName URLString:URLString parameters:parameters headers:nil uploadProgress:nil downloadProgress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        finished(responseObject,nil);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        finished(nil,error);
//        NSLog(@"%@",error);
//    }];
//    [dataTask resume];
    
    NSLog(@"%@",self.baseURL);
    
    NSString *urlString = [self.baseURL.absoluteString stringByAppendingString:URLString];
    NSLog(@"%@",urlString);
    NSURL *url = [NSURL URLWithString:urlString];
    
    NSString *bearerStart = @"Bearer ";
    NSString *tokenBearer = [bearerStart stringByAppendingString:token];
    NSLog(@"%@",tokenBearer);
    
    NSData* dataParam = [parameters dataUsingEncoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url
                                                               cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                           timeoutInterval:1000];
    
    
    //[request setValue:@"bearer your_access_token" forHTTPHeaderField:@"Authorization"];
    [request setValue:tokenBearer forHTTPHeaderField:@"Authorization"];
    
    [request setHTTPMethod:methodName];
    [request setHTTPBody:dataParam];
    
    NSURLSession *requestSessions = [NSURLSession sharedSession];
    NSURLSessionDataTask *requestTasks = [requestSessions dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //NSLog(@"data ======= %@, response ======= %@, error ======= %@",data ,response, error);
        
        if(error==NULL){
            NSString *resultStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"响应数据正常");
            NSLog(@"-------------data start---------------");
            NSLog(@"%@",resultStr);
            NSLog(@"-------------data end-----------------");
            finished(data,nil);
        }else{
            NSLog(@"响应数据出错了");
            NSLog(@"%@",error);
            finished(nil,error);
        }
    }];
    [requestTasks resume];
}

@end
